package main

import (
	tls "ac-common-go/tls"
	"bufio"
	"fmt"
	"net"
	"strconv"
	"strings"
	"time"
)

var paramString_101 = "{\"id\":101,\"wid\":\"wifiid\",\"ver\":\"CCCCC\"}"
var loc, _ = time.LoadLocation("UTC")

func main() {
	wifiId := "8650401000100010040000000e4eeeeeeeee"
	serverAddr := "frig-eu-link.hijuconn.com:443"
	connectTimeoutSecondsDuration := time.Second * time.Duration(5)

	fmt.Println("***************start********************")
	fmt.Println(fmt.Sprintf("begin to connect to AWS GA:%s for wifiId %s at %v", serverAddr, wifiId, time.Now().In(loc).Format(time.RFC1123)))
	terminal(serverAddr, connectTimeoutSecondsDuration, wifiId)
}

func terminal(serverAddr string, connectTimeoutSeconds time.Duration, wifiId string) {
	defer func() {
		if pErr := recover(); pErr != nil {
			fmt.Println(fmt.Sprintf("%+v=> wifiId:%s have panic err:%+v", time.Now(), wifiId, pErr))
		}
	}()

	connectCount := 0
	for {
		var connTls *tls.Conn
		var err error
		conf := &tls.Config{
			//InsecureSkipVerify: true,
			CipherSuites: []uint16{
				tls.TLS_RSA_WITH_AES_256_CBC_SHA256,
				tls.TLS_RSA_WITH_AES_256_CBC_SHA,
				tls.TLS_RSA_WITH_AES_128_CBC_SHA256,
				tls.TLS_RSA_WITH_AES_128_CBC_SHA,
			},
			MinVersion: tls.VersionTLS12,
		}
		conf.ServerName = ""
		connTls, err = tls.DialWithDialer(&net.Dialer{Timeout: connectTimeoutSeconds}, "tcp", serverAddr, conf)
		if err != nil {
			fmt.Println(fmt.Sprintf("%v failed to connect to %s in %v at %v, will reconnect after 5 seconds...", time.Now(), serverAddr, connectTimeoutSeconds, time.Now().In(loc).Format(time.RFC1123)))
			time.Sleep(time.Second * time.Duration(5))
			continue
		}
		connectCount++

		var bw *bufio.Writer
		var br *bufio.Reader
		bw = bufio.NewWriter(connTls)
		br = bufio.NewReader(connTls)

		token, err := sendFake101Message(bw, br, wifiId, connectCount, serverAddr)
		time.Sleep(time.Second * time.Duration(1))
		if token == "" {
			continue
		}
		_ = connTls.Close()
	}
}

func sendFake101Message(bw *bufio.Writer, br *bufio.Reader, wifiId string, count int, serverAddr string) (string, error) {
	param := strings.Replace(paramString_101, "wifiid", wifiId, -1)
	md5Sign := strconv.Itoa(count)
	param101 := "HS" + param + md5Sign + "\r\n"
	bw.WriteString(param101)
	bw.Flush()
	fmt.Println(fmt.Sprintf("%+v=>sent 101 request: %s of wifiId %s to %s at %v", time.Now(), param101, wifiId, serverAddr, time.Now().In(loc).Format(time.RFC1123)))
	_, err := br.ReadString('\n')
	if err != nil {
		return "", err
	}
	return "", nil
}
